package com.ls.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ls.entity.Trade;
import com.ls.mapper.TradeMapper;
import com.ls.service.ITradeService;
import com.ls.utils.ResultData;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 行业 服务实现类
 * </p>
 *
 * @author pengyu
 * @since 2024-10-12
 */
@Service
@RequiredArgsConstructor
public class TradeServiceImpl extends ServiceImpl<TradeMapper, Trade> implements ITradeService {
    /** 查询行业 */
    @Override
    public ResultData getTrade() {
        List<Trade> tradeList = this.list();
        // 构建父子关系映射
        Map<Long, List<Trade>> parentMap = new HashMap<>();
        for (Trade trade : tradeList) {
            parentMap.computeIfAbsent(trade.getParentId(), k -> new ArrayList<>()).add(trade);
        }

        // 递归构建树形结构
        List<Trade> tree = buildTree(0L, parentMap);
        return ResultData.successData(tree);
    }

    private List<Trade> buildTree(Long parentId, Map<Long, List<Trade>> parentMap) {
        List<Trade> nodes = parentMap.getOrDefault(parentId, new ArrayList<>());
        for (Trade node : nodes) {
            node.setChildren(buildTree(node.getTradeId(), parentMap));
        }
        return nodes;
    }
}
